//
//  InviteViewController.swift
//  foodApp1
//
//  Created by JennyShi on 2018/3/6.
//  Copyright © 2018年 Apple Inc. All rights reserved.
//

import UIKit
import os.log
import Hyphenate
import MobileCoreServices
import MBProgressHUD
import Alamofire

class InviteViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var friendList = [Friend]()
    
    //传进来的参数
    var sourceViewControllerType : Int = EnStatic.fromEventListToReplyFriend
    var eventId : String?       //reload backend data with eventId
    var guestDictionaryArray: [AnyObject] = [AnyObject]()

    //变量
    var hasEventId : Bool = false

    @IBOutlet weak var invTableView: UITableView!
    
    @IBAction func cancelButtonClicked(_ sender: UIBarButtonItem) {
        navigationController?.popViewController(animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = " "
        
        //自定义导航栏左侧的cancel按钮
        let cancelButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Back"), style: .plain, target: self, action: #selector(cancelButtonClicked))
        self.navigationItem.leftBarButtonItem = cancelButtonItem

        // 设置传进来的参数
        if sourceViewControllerType == EnStatic.fromEventListToReplyFriend
            || sourceViewControllerType == EnStatic.fromEventListToSeeFriendsReply
            || sourceViewControllerType == EnStatic.fromNotificationToReplyFriendThenToMainPage {
            if eventId == eventId {
                if eventId != nil {
                    if !(eventId?.isEmpty)! {
                        hasEventId = true
                    }
                }
            }
        } else {
            hasEventId = false
        }

        //获取屏幕大小
        invTableView.frame = UIScreen.main.bounds

        //去掉背景线条显示
        self.invTableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
//        self.invTableView.separatorColor = UIColor.clear;
        self.invTableView.separatorInset =
            UIEdgeInsetsMake(10, 20, 10, 20);
        //不允许多选
        invTableView.allowsMultipleSelection = false
        
        invTableView.delegate = self
        invTableView.dataSource = self
        
        //下拉刷新
        invTableView.refreshControl = UIRefreshControl()
        invTableView.refreshControl?.attributedTitle = NSAttributedString(string: EnStatic.getWord(keyWord: "Pull down to refresh"))
        invTableView.refreshControl?.addTarget(self, action: #selector(pullDownRefreshing), for: UIControlEvents.valueChanged)

        //loadFriendList，从guestDictionaryArray中读取
        loadFriendList()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //下拉刷新
    @objc func pullDownRefreshing(){
        if hasEventId {
            getEventById(eventId : eventId!)
        }
    }

    func myAlert(message000 : String) {
        let alertController = UIAlertController(title: "",message: EnStatic.getWord(keyWord: message000), preferredStyle: .alert)
        let okAction = UIAlertAction(title: EnStatic.getWord(keyWord: "OK"), style: .default, handler: {
            action in
            print("ok clicked")
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return friendList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellIdentifier = "InviteTableViewCell"
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? InviteTableViewCell  else {
            fatalError("The dequeued cell is not an instance of MeTableViewCell.")
        }
        
        // Fetches the appropriate meal for the data source layout.
        let me = friendList[indexPath.row]
        
        cell.friendName.text = getNickNameWithUsername(username: me.userName)
        cell.selectedBackgroundView = UIView()
        cell.selectedBackgroundView?.backgroundColor = UIColor.clear

        switch me.goingOrNot {
        case "not going":
            cell.backgroundColor = OrangeRedColor
        case "going":
            cell.backgroundColor = BrightBlueColor
        case "unread":
            cell.backgroundColor = WhiteColor
        default:
            cell.backgroundColor = TextViewBorderColor
        }

        cell.friendDescription.text = EnStatic.getWord(keyWord: me.goingOrNot)

        return cell

    }
    

    //MARK: Private Methods
    
    private func loadFriendList() {
        if guestDictionaryArray.count > 0 {
            friendList.removeAll()
            for guest in guestDictionaryArray {
                let guestName = guest["guest"]
                let guestStatus = guest["status"]
                let friend = Friend(userName: guestName as! String,goingOrNot: guestStatus as! String)
                friendList.append(friend!)
            }
        }
    }
    
    //按照传入的eventId获得别人邀请自己的event详情
    private func getEventById(eventId : String) {
        
        let urlstr = "event?eventId=" + eventId
        let cuHTTP = CUHTTP.instance()
        cuHTTP.makeGetData(url: urlstr, success: {response in
            print("Response String: \(String(describing: response?.result.value))")
            print(response?.response?.statusCode ?? "??")
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: Any]
                print(json ?? "??")
                if let loopE0 = json?["events"] {
//                    if let loopE = (loopE0 as? [String: Any]) {
//                        print(loopE)
//                        //guestStatus：把python版JSONString转化为标准JSONString
//                        let guestStatus000 = loopE["guestStatus"] as! String
//                        print(guestStatus000)
//                        let guestStatus111 = guestStatus000.replacingOccurrences(of: "u'", with: "\"", options: .literal, range: nil)
//                        print(guestStatus111)
//                        let guestStatus = guestStatus111.replacingOccurrences(of: "'", with: "\"", options: .literal, range: nil)
//                        print(guestStatus)
//                        let tmpDictionaryArray = guestStatus.parseJSONString
//                        if tmpDictionaryArray != nil {
//                            self.guestDictionaryArray = tmpDictionaryArray as! [AnyObject]
//                            print(self.guestDictionaryArray)
//                            self.loadFriendList()
//                            self.invTableView.refreshControl?.endRefreshing()
//                            self.invTableView.reloadData()
//                        }
//                    }
                }
            }
        },
                           failure:{ response in
                            print(response ?? " ")
                            self.myAlert(message000: "get data failed")
        }
        )
        
    }

    func getNickNameWithUsername(username : String) -> String {
        let entity = EMUserProfileManager.sharedInstance.getUserProfileByUsername(username: username)
        if entity?.nickname != nil && (entity?.nickname?.count)! > 0 {
            return (entity?.nickname)!
        }
        return username
    }
    
}

